/*
AlliedBridge Content Management System
Copyright (C) 2006 AlliedBridge

This program is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software Foundation;

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.volume4.alliedbridge.model.gallery;

import java.io.*;
import java.sql.*;
import java.util.Iterator;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;

import org.volume4.utils.ServletUtilities;
import org.apache.commons.fileupload.*;

public class CreateGalleryItem extends HttpServlet {

    // Should the following three String declarations be private or final?
    // Should they be in an interface?
    public String DRIVER, URL, USER, PASS, fieldName, fieldData, fileName, fileFieldName, dest_folder, db_url, app_root,
    insert_table, messageSuccess, messageFailed;    
    public String folder = "/opt/tomcat5/webapps/mc/media/media_gallery/";
    public String tempFolder = "/opt/tomcat5/webapps/mc/media/temp/";
    public String caption, credit, issued, std_img, press_img;

    public void init() throws ServletException {
        ServletContext context = getServletContext();
        DRIVER = context.getInitParameter("driver");
        URL = context.getInitParameter("mc_dburl");
        USER = context.getInitParameter("mc_dbuser");
        PASS = context.getInitParameter("mc_dbpass");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        Connection con = null;
        // These need to be moved to a properties file.
        messageSuccess = "Gallery item successfuly created.";
        messageFailed = "Gallery item creation failed.";
        db_url = "../media/media_gallery/";

        try {

            DiskFileUpload upload = new DiskFileUpload();
            upload.setSizeThreshold(4096);
            upload.setRepositoryPath(tempFolder);
            upload.setSizeMax(-1);

            // Parse the request
            List fileItems = upload.parseRequest(request);

            // Process the uploaded fields
            Iterator iter = fileItems.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.isFormField()) {

                    if (item.getFieldName().equals("caption")) {
                        caption = ServletUtilities.filter(item.getString());
                    } else if (item.getFieldName().equals("credit")) {
                        credit = ServletUtilities.filter(item.getString());
                    }
                    // Note that issued is a Date. Need to reformat String to Date.
                    else if (item.getFieldName().equals("issued")) {
                        issued = ServletUtilities.filter(item.getString());
                    }
                } else {
                    if (item.getFieldName().equals("std_img")) {
                        int i = item.getName().lastIndexOf('\\');
                        std_img = db_url + ServletUtilities.filter(item.getName().substring(i + 1));
                        File savedFile = new File(folder, ServletUtilities.filter(item.getName().substring(i + 1)));
                        item.write(savedFile);
                    } else if (item.getFieldName().equals("press_img")) {
                        int i = item.getName().lastIndexOf('\\');
                        press_img = db_url + ServletUtilities.filter(item.getName().substring(i + 1));
                        File savedFile = new File(folder, ServletUtilities.filter(item.getName().substring(i + 1)));
                        item.write(savedFile);
                    }
                }
            }

            Class.forName(DRIVER);
            con = DriverManager.getConnection(URL, USER, PASS);

            String query = "INSERT INTO ab_media_gallery " +
                    "(std_img,press_img,caption,credit,issued)" +
                    "VALUES ('" + std_img + "', " +
                    "'" + press_img + "', " +
                    "'" + caption + "', " +
                    "'" + credit + "', " +
                    "'" + issued + "')";

            PreparedStatement stmt = con.prepareStatement(query);

            int result = stmt.executeUpdate(query);

            app_root = request.getContextPath();
            response.sendRedirect(app_root + "/application/application_messages/process_result.jsp?message=" + messageSuccess);

        } catch (SQLException ex) {
            System.out.println("\nERROR:------ SQLException -----\n");
            while (ex != null) {
                System.out.println("Message: " + ex.getMessage());
                System.out.println("SQLState: " + ex.getSQLState());
                System.out.println("ErrorCode :" + ex.getErrorCode());
                ex = ex.getNextException();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (con != null)
                    con.close();
            } catch (SQLException ex) {
                System.out.println("\nERROR:------ SQLException -----\n");
                System.out.println("Message: " + ex.getMessage());
                System.out.println("SQLState: " + ex.getSQLState());
                System.out.println("ErrorCode :" + ex.getErrorCode());
            }
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}